﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;

using Newtonsoft.Json;
using SH.STD.Model;
using Cmn;
using SH.STD.DataProvider;
using System.Web.SessionState;


namespace SH.STD.Web.Handler
{
    /// <summary>
    /// Summary description for Permission
    /// </summary>
    public class Permission : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetNoStore();
            context.Response.ContentType = "application/json;charset=gb2312";

            switch (context.Request.Params["action"])
            {
                case "loadData":
                    context.Response.Write(ConvertToJsonString(context.Request.Params["id"]));
                    break;
                case "addData":
                    context.Response.Write(AddData(context.Request.Params["jsonDataString"]));
                    break;
                case "removeData":
                    context.Response.Write(RemoveData(context.Request.Params["id"]));
                    break;
                case "updateData":
                    context.Response.Write(UpdateData(context.Request.Params["jsonDataString"]));
                    break;
            }
        }

        private string AddData(string jsonDataString)
        {
            return UpdateData(jsonDataString);
        }
        private string ConvertToJsonString(string id)
        {
            var sql = @"
select a.ID,a.Name as UserName,d.Name as DepName,b.FormID
from usrUser a
left join UserRight b
on a.ID=b.UserID
left join Form c
on b.FormID=c.ID
left join Department d
on a.DepID=d.ID
where a.status=1 and a.ID='" + id + "'";
            var datas = DataAccess.GetDataTable(sql);
            var dt = new DataTable();
            dt.Columns.Add("UserID");
            dt.Columns.Add("UserName");
            dt.Columns.Add("DepName");
            dt.Columns.Add("FormIDs");

            var group = new Dictionary<string, HashSet<string>>();
            for (int i = 0; i < datas.Rows.Count; i++)
            {
                var key = String.Format("{0}|{1}|{2}", datas.Rows[i][0], datas.Rows[i][1], datas.Rows[i][2]);
                if (!group.ContainsKey(key))
                {
                    group.Add(key, new HashSet<string>());
                }
                group[key].Add(datas.Rows[i][3].ToString());
            }
            foreach (var item in group)
            {
                var keys = item.Key.Split('|');
                dt.Rows.Add(keys[0], keys[1], keys[2], String.Join(",", item.Value.ToArray()));
            }
            return DataAccess.ConvertToJSON(dt, "Permissions");
        }
        private string UpdateData(string jsonDataString)
        {
            JavaScriptObject item = (JavaScriptObject)JavaScriptConvert.DeserializeObject(jsonDataString);
            var delSql = "delete from UserRight where UserID='" + RepsonseInfo.Decode(item["ID"].ToString()) + "'";
            DB.execSql(delSql);
            var userID = RepsonseInfo.Decode(item["ID"].ToString());
            var formIDs = RepsonseInfo.Decode(item["FormIDs"].ToString()).Split('|');
            var insertSql = @"insert into UserRight (UserID,FormID,LastModifiedBy) values (@UserID,@FormID,@LastModifiedBy)";
            foreach (var formID in formIDs)
            {
                var cmdParas = new SqlParameter[]
                    {
                        new SqlParameter("UserID",RepsonseInfo.Decode(item["ID"].ToString())),
                        new SqlParameter("FormID",formID),
                        new SqlParameter("LastModifiedBy",Cmn.Session.GetUserID()),
                    };
                DB.execSql(insertSql, cmdParas);
            }

            return JavaScriptConvert.SerializeObject(new RepsonseInfo { MSG = item["ID"].ToString() });
        }

        private string RemoveData(string jsonDataString)
        {
            JavaScriptObject item = (JavaScriptObject)JavaScriptConvert.DeserializeObject(jsonDataString);
            var cmdParas = new SqlParameter[]
                    {
                        new SqlParameter("ID",RepsonseInfo.Decode(item["ID"].ToString())),
                    };
            var sql = "update usrUser set status=0 where ID=@ID";
            Cmn.DB.execSql(sql, cmdParas);

            return JavaScriptConvert.SerializeObject(new RepsonseInfo { MSG = item["ID"].ToString() });
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}